const express = require("express");
const app = express();
const router = express.Router();

const {mysql , executeQuery} = require("../../mysql");


// 添加课程
router.post("/create-course", async (req, res) => {
    const courses = req.body; // 假设前端将多条课程信息放在 courses 数组中
    console.log(req.body);
    try {
        if (!courses || courses.length === 0) {
            return res.status(400).json({ 
                code: 400,
                error: '没有提供要插入的课程信息。' 
            });
        }

        const sql = `INSERT INTO tb_course (Course_Name, Teacher_Name, Major, Major_ID, Department_ID, Grade)  VALUES (?, ?, ?, ?, ?, ?)`;

        /**
         * 循环
         */
        const insertPromises = courses.map(async course => {
            const { courseName, teacherName, grade,  major_ID, Department_ID } = course;

            // 假设这里也需要获取专业信息
            const majorInfo = await getMajorInfo(major_ID);

            if (!majorInfo) {
                throw new Error('未找到对应的专业信息');
            }

            const values = [
                courseName,
                teacherName,
                majorInfo.Major_Name,
                major_ID,
                Department_ID,
                grade,
            ];

            // 执行插入操作
            return executeQuery(sql, values);
        });

        // 等待所有插入操作完成
        const results = await Promise.all(insertPromises);

        // 检查所有结果
        const successfulInserts = results.every(result => result);

        if (successfulInserts) {
            res.json({
                success: true,
                code: 200,
                message: '成功插入所有课程信息'
            });
        } else {
            res.status(500).json({ 
                success: false,
                msg: '部分或全部课程插入失败，请检查日志'
            });
        }
    } catch (error) {
        if (error.code === 'ER_DUP_ENTRY') {
            console.error('重复数据插入错误：', error.message);
            res.status(200).json({ 
                success: false,
                error: '重复的课程信息已存在，请检查数据'
            });
        } else {
            console.error('插入课程信息失败：', error.stack);
            res.status(500).json({ 
                success: false,
                error: '部分或全部课程插入失败，请检查日志'
            });
        }
    }
});


// 异步函数：根据 major_ID 查询专业信息
async function getMajorInfo(majorId) {
    const sql = 'SELECT * FROM tb_major WHERE Major_ID = ?';
    
    let results = await executeQuery(sql, [majorId]); // 将 majorId 包装成数组传递给 executeQuery
    if (results.length > 0) {
        return results[0];
    } else {
        return null; // 未找到对应的专业信息
    }
}


module.exports = router;


